package com.lagou.dubbo.web.util;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 给提供者传递ip
 */
@Activate(group = CommonConstants.CONSUMER)
public class TransportIpFilter implements Filter {

    private static HttpServletRequest request;
    public static void setRequest(HttpServletRequest request) {
        TransportIpFilter.request = request;
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        if (request == null) {
            return invoker.invoke(invocation);
        }
        String ip = "127.0.0.1";
        try {
            ip = IPUtils.getIpAddr(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RpcContext.getContext().setAttachment("local_ip", ip);
        return invoker.invoke(invocation);
    }
}
